import './View.scss';
import './Edit.scss';

import React, { PureComponent as Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { formatTime } from '../../../../common.js';

// antd
import { Row, Col, Button, Modal, Table, message } from 'antd';
const confirm = Modal.confirm;

import AddMethodForm from "./AddMethodForm";
import ChangeInterfaceForm from "./ChangeInterfaceForm";

import {
  /* TTC ADD */
  fetchInterfaceInfo,
  fetchInterfaceListByCondition,
  /*  TTC ADD ^^^^^    */
  deleteInterfaceData,
  fetchInterfaceListMenu
} from '../../../../reducer/modules/dubboInterface.js';

import {  fetchGroupMemberList } from '../../../../reducer/modules/group.js'

import { Link } from "react-router-dom";
import axios from "axios";
import moment from "moment";

//redux相关数据
@connect(
    state => {
        return {
            curData: state.dubboInterface.curdata,
            curProject: state.dubboProject.currProject,
            infBaseInfo:state.dubboInterface.infBaseInfo,
            methodList:state.dubboInterface.methodList,
            uid:state.user.uid,
            role:state.user.role,
            memberList:state.group.member
        };
    },
    {
        fetchInterfaceInfo,
        fetchInterfaceListByCondition,
        deleteInterfaceData,
        fetchInterfaceListMenu,
      fetchGroupMemberList
    }
)




class InterfaceInfo extends Component {

  //构造函数
  constructor(props) {
    super(props);
    this.state = {
      add_method_visible: false,
      change_visible: false,
      delete_visible: false,
      init: true,
      enter: false,
      data: [],
      infid: null, // *** ！！！这个infid很重要，不能删除 ***
      total: null,
      current: 1,
      infBaseinfo: null,
      methodList: [],
      cusername:null,
      eusername:null
    };
  }

    //数据类型校验
    static propTypes = {
        match: PropTypes.object,
        curProject: PropTypes.object,
        curData: PropTypes.object,
        needRefresh:PropTypes.bool,
        fetchInterfaceInfo:PropTypes.func,
        fetchInterfaceListMenu:PropTypes.func,
        deleteInterfaceData : PropTypes.func,
        // TTC ADD
        infBaseInfo: PropTypes.object,
        methodList: PropTypes.array,
      fetchGroupMemberList:PropTypes.func,
      fetchInterfaceListByCondition:PropTypes.func,
      uid:PropTypes.number,
      memberList: PropTypes.array,
      role:PropTypes.string,
        // TTC ADD ^^^^
        infid:PropTypes.object,
        cusername:PropTypes.string,
        eusername:PropTypes.string

  };

    // 加载页面触发
    componentWillMount = async () => {
      await this.props.fetchGroupMemberList(this.props.curProject.groupid);
        this.actionId = this.props.match.params.actionId;
        await this.handleRequest(this.props);

  };

  componentDidMount() {
    if (!this.props.curData.title && this.state.init) {
      this.setState({ init: false });
    }
  }

  componentWillReceiveProps(nextProps) {
    let _actionId = nextProps.match.params.actionId;

    if (this.actionId !== _actionId) {
      this.actionId = _actionId;
      this.setState(
        {
          current: 1
        },
        () => this.handleRequest(nextProps)
      );
    }
  }


  /**
   * 请求数据，初次载入界面和更新从父组件收到新的props后都会执行
   * @returns {Promise<void>}
   */
  async handleRequest() {

    const { params } = this.props.match;
    if (!params.actionId) {

    } else if (isNaN(params.actionId)) {
      let infid = params.actionId.substr(4);
      this.setState({ infid: +infid });

      await this.props.fetchInterfaceInfo(infid);
      let cusername = await this.getUsernameById(this.props.infBaseInfo.cuserid);
      let eusername = await this.getUsernameById(this.props.infBaseInfo.euserid);

            this.setState({
                cusername:cusername,
                eusername:eusername
            });

        }

  }


  /**
   * 从AddMethodForm获取的data
   * 根据data中的数据进行方法的添加
   * @param data
   * @returns {Promise<void>}
   */
    handleAddMethod = async data => {

        let params = {
          infid: this.state.infid,
          cname: data.cname,
          mname:data.mname,
          inname:data.inname,
          outname:data.outname,
          status:data.status,
          ischl:data.ischl,
          projectid:this.props.curProject._id
        };

        await axios.post('/api/dubbomethod/add_method', params).then(res => {
      // axios.post('/api/dubbomethod/add', params).then(res => {
            if (res.data.errcode !== 0) {
                return message.error(res.data.errmsg);
            }
            message.success('方法添加成功');
            this.setState({
                add_method_visible: false
            });
        });

      this.props.fetchInterfaceListMenu(this.props.curProject._id);
      this.props.fetchInterfaceInfo(this.state.infid);

    };


  /**
   * 从ChangeInterfaceForm获取的data
   * 根据data中的数据对接口信息进行更新
   * @param data
   */
    handleChangeInterface = async data => {

      let params = {
      infid: this.state.infid,
      cname: data.cname,
      classname: data.classname,
      desc: data.desc,
      onlinedate: data.onlinedate?moment(data.onlinedate).format('YYYY-MM-DD'):null,
      status: data.status
    };

      // server/controllers/dubboInterface.js没有提供up方法，自定义upInterface方法
      axios.post('/api/dubbo_interface/up_interface', params).then(res => {
          if (res.data.errcode !== 0) {
          return message.error(res.data.errmsg);
        }

        message.success('接口更新成功');
          this.props.fetchInterfaceInfo(this.state.infid).then( r =>{
              this.getUsernameById(r.payload.data.data.infBaseInfo.euserid).then(username =>{
                  this.setState({
                      eusername:username
                  })
              });

            this.props.fetchInterfaceListMenu(this.props.curProject._id);
          });

          this.setState({
          change_visible: false
        });

      });


      // this.props.fetchInterfaceInfo(this.state.infid);

  };


  /**
   * 点击 删除方法 按钮后，执行的逻辑
   * @param infid
   */
  showDelConfirm = infid => {
    let that = this;


    let projectId = that.props.match.params.id;

    // console.log(projectId);

    const ref = confirm({
      title: '确定删除此接口吗？',
      content: '温馨提示：该操作会删除该接口下所有方法，接口删除后无法恢复',
      okText: '确认',
      cancelText: '取消',
      async onOk() {
        await that.props.deleteInterfaceData(infid, projectId);
        await that.props.fetchInterfaceListMenu(that.props.curProject._id);
        await that.props.fetchInterfaceListByCondition(that.props.curProject._id,null,null,"");
        that.props.history.push('/dubboproject/' + that.props.match.params.id + '/interface/api');
        ref.destroy();

      },
      onCancel() { }
    });
  };

  /**
   * 根据 用户ID 获取 用户名
   * @param userId
   * @returns {Promise<*>}
   */
    async getUsernameById(userId){
        if(userId) {
            let r = await axios.get('/api/user/find?id=' + userId);
            return r.data.data.username;
        }
    }

  /**
   * 检查删除权限，有权限返回0，无权限返回1
   */
  checkDeleteAuth = () => {
    // console.log(this.props);
    return 0;
  };

  //渲染函数
  render() {

    /*各种数据定义，逻辑定义*/

    // let deleteAuth = 1;
    // let role = '';
    // let memberList = this.props.memberList;
    // for(let i = 0;i < memberList.length;i ++){
    //   if(this.props.uid === memberList[i].uid){
    //     role = memberList[i].role;
    //     break;
    //   }
    // }
    // if(this.props.role === 'admin' || this.props.uid === this.props.infBaseInfo.cuserid || role === 'admin' || role === 'owner'){
    //   deleteAuth = 0;
    // }

    const getStatusStype = (status) => {
      const statusMap = {
        '设计中': 'design',
        'sit测试': 'insit',
        'uat测试': 'inuat',
        '已上线': 'online'
      };
      return statusMap[status]
    };

    let {cname,status,onlinedate,classname,ctime,etime,desc,cuserid,euserid} = this.props.infBaseInfo;

    switch (status) {
      case 0:
        status = '设计中';
        break;
      case 1:
        status = 'sit测试';
        break;
      case 2:
        status = 'uat测试';
        break;
      case 3:
        status = '已上线';
        break;
      default:
        status = '未知';
    }

    /*  方法列表的列定义 */
        const columns = [
          {
            title: '方法中文名',
            dataIndex: 'cname',
            key: 'cname',
            width: 30,
            render: (text, item) => {
              return (
                <Link to={'/dubboproject/' + this.props.curProject._id + '/interface/api/' + item._id}>
                  <span className="path">{text}</span>
                </Link>
              );
            }
          },
            {
                title: '方法名称',
                dataIndex: 'mname',
                key: 'mname',
                width: 60,
                render: (text, item) => {
                    return (
                      <Link to={'/dubboproject/' + this.props.curProject._id + '/interface/api/' + item._id}>
                        <span className="path">{text}</span>
                      </Link>
                    );
                }
            },
          {
            title: '测试状态',
            dataIndex: 'status',
            key: 'status',
            width: 30,
            render: (text) => {
              let status = '未知';
              let className = 'path';
              switch (text) {
                case 0:
                  status = '设计中';
                  className="tag-status design";
                  break;
                case 1:
                  status = 'sit测试';
                  className="tag-status insit";
                  break;
                case 2:
                  status = 'uat测试';
                  className="tag-status inuat";
                  break;
                case 3:
                  status = '已上线';
                  className="tag-status online";
              }
              return (
                <span className={className}>{status}</span>

              );
            }
          },
          {
            title: '上线时间',
            dataIndex: 'onlinedate',
            key: 'onlinedate',
            width: 30,
            render: (text) => {
              return (
                <span className="path">{text}</span>
              );
            }
          },
          {
            title: '是否渠道交易',
            dataIndex: 'ischl',
            key: 'ischl',
            width: 30,
            render: (text) => {
              let ischl = '未知';
              switch (text) {
                case 0:
                  ischl = '否';
                  break;
                case 1:
                  ischl = '是';
              }
              return (
                <span className="path">{ischl}</span>

              );
            }
          },
          {
            title: '是否api',
            dataIndex: 'isapi',
            key: 'isapi',
            width: 30,
            render: (text) => {
              let isapi = '未知';
              switch (text) {
                case 0:
                  isapi = '否';
                  break;
                case 1:
                  isapi = '是';
              }
              return (
                <span className="path">{isapi}</span>
              );
            }
          }
      ];


    //  获取方法列表的数据
    let dataSource = [];
    // let total = 0;
    dataSource = this.props.methodList;

    dataSource = dataSource.map(item => {
      item.key = item._id;
      return item;
    });

    /**/

    //   渲染数据 **********
    return (
      <div className="caseContainer">

        <h2 className="interface-title" style={{ marginTop: 0 }}>
          接口基本信息
        </h2>

        <div className="panel-view">

          <Row className="row">
            <Col span={3} className="colKey">
              接口名称：
            </Col>
            <Col span={5} className="colName">
              {cname}
            </Col>
            <Col span={3} className="colKey">
              接口状态：
            </Col>
            <Col span={5} className={'tag-status ' + getStatusStype(status)}>
              {status}
            </Col>
            <Col span={3} className="colKey">
              上线时间：
            </Col>
            <Col span={5}>
              {/*{onlinedate ? new Date(onlinedate).getFullYear() + '年' + (new Date(onlinedate).getMonth() + 1) + '月' + new Date(onlinedate).getDate() + '日' : ''}*/}
              {onlinedate}
            </Col>
          </Row>

          <Row className="row">
            <Col span={4} className="colKey">
              接口类名：
            </Col>
            <Col span={20} className="colName">
              {classname}
            </Col>
          </Row>

          <Row className="row">
            <Col span={5} className="colKey">
              创建时间：
            </Col>
            <Col span={5} className="colName">
              {formatTime(ctime)}
            </Col>
            <Col span={3} className="colKey">
              创建者：
            </Col>
            <Col span={3} className="colName">
              {cuserid == undefined ? '' :
                (<Link className="user-name" to={'/user/profile/' + cuserid}>
                  <img src={'/api/user/avatar?uid=' + cuserid} className="user-img" />
                  {this.state.cusername}
                </Link>)
              }
            </Col>
          </Row>
          <Row className="row">
            <Col span={5} className="colKey">
              修改时间：
            </Col>
            <Col span={5} className="colName">
              {etime?formatTime(etime):null}
            </Col>
            <Col span={3} className="colKey">
              修改者：
            </Col>
            <Col span={3} className="colName">
              {euserid == undefined ? '' :
                (<Link className="user-name" to={'/user/profile/' + euserid}>
                  <img src={'/api/user/avatar?uid=' + euserid} className="user-img" />
                  {this.state.eusername}
                </Link>)
              }
            </Col>
          </Row>

          <Row className="row">
            <Col span={4} className="colKey">
              接口描述：
            </Col>
            <Col span={20} className="colName">
              {desc}
            </Col>
          </Row>

        </div>

        <div align="center">
          <Button
            // disabled={isDisabled}
            type="primary"
            onClick={() => this.setState({ add_method_visible: true })}
          >
            添加方法
          </Button>
          &nbsp;
          &nbsp;
          &nbsp;
          <Button
            // disabled={isDisabled}
            type="primary"
            onClick={() => this.setState({ change_visible: true })}
          >
            修改
          </Button>
          &nbsp;
          &nbsp;
          &nbsp;
          <Button
            // disabled={deleteAuth}
            type="danger"
            onClick={e => {
              e.stopPropagation();
              this.showDelConfirm(this.state.infid);
            }}
          >
            删除
          </Button>
        </div>

        <h2 className="interface-title" style={{ marginTop: 0 }}>
          方法列表 ({this.props.methodList.length}个）
        </h2>

        {this.state.add_method_visible && (
        <Modal
                      width={800}
                      title="添加方法"
                      visible={this.state.add_method_visible}
                      onCancel={() => this.setState({ add_method_visible: false })}
                      footer={null}
                      className="addmethodmodal"
                  >
          <AddMethodForm
                          onCancel={() => this.setState({ add_method_visible: false })}
                          onSubmit={this.handleAddMethod}
                      />
        </Modal>
              )}

        {this.state.change_visible && (
        <Modal
                title="修改"
                visible={this.state.change_visible}
                onCancel={() => this.setState({ change_visible: false })}
                footer={null}
                className="changemodal"
              >
          <ChangeInterfaceForm
                  onCancel={() => this.setState({ change_visible: false })}
                  onSubmit={this.handleChangeInterface}
                />
        </Modal>
            )}

        <Table
          className="table-methodlist"
          // pagination={pageConfig}
          columns={columns}
          onChange={this.handleChange}
          dataSource={dataSource}
        />

      </div>
    );

  }

}

export default InterfaceInfo;
